package com.xnyzc.lhy.didi.controller.platform;

import com.alibaba.fastjson.JSON;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.didi.config.XieChengConfig;
import com.xnyzc.lhy.didi.entity.param.xiecheng.request.*;
import com.xnyzc.lhy.didi.entity.param.xiecheng.response.XieChengResponse;
import com.xnyzc.lhy.didi.service.xiecheng.RequsetService;
import com.xnyzc.lhy.didi.service.xiecheng.XcRequsetService;
import com.xnyzc.lhy.didi.util.XieChengUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;

@Api(value = "携程订单API", tags = {"携程订单API"})
@Slf4j
@RestController
@RequestMapping("oa/xc/")
public class XieChengController {

    //供应商ID
    @Value("${global.xc.venderId}")
    private String venderId;

    //携程密钥
    @Value("${global.xc.secretKey}")
    private String secretKey;


    @Autowired
    private XcRequsetService requestService;

    @RequestMapping(value = "{channel}/{action}/{version}/{timestamp}/{sign}", method = RequestMethod.POST)
    @ResponseBody
    public XieChengResponse queryProduct(@PathVariable("channel") String channel, @PathVariable("action") String action, @PathVariable("version") String version,
                                         @PathVariable("timestamp") String timestamp,
                                         @PathVariable("sign") String sign,
                                         HttpServletRequest request) throws ParseException {
        String body = "";
        BufferedReader br = null;
        try {
            br = request.getReader();
            String str = "";
            while ((str = br.readLine()) != null) {
                body += str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        log.info("携程channel-" + channel);
//        log.info("携程action-" + action);
//        log.info("携程version-" + version);
//        log.info("携程timestamp-" + timestamp);
//        log.info("携程sign-" + sign);
//        log.info("携程body-" + body);
        String msign = XieChengUtil.getSign(venderId, channel, version, timestamp, body.length(), secretKey);
        if (msign.equalsIgnoreCase(sign)) {
            String params = null;
            try {
                //log.info("Body-" + body);
                params = XieChengUtil.decodeDES(secretKey, body);
                //log.info("params-" + params);
            } catch (Exception e) {
                throw new PangException(e.getMessage());
            }
            //接口的处理器
            return handleAction(action, params);
        } else {
            XieChengResponse response = XieChengResponse.error();
            response.setMessage("校验失败");
            return response;
        }
    }

    /**
     * 总接口的处理器
     * @param action 接口类型
     * @param body 传入的参数
     * @return
     */
    private XieChengResponse handleAction(String action, String body) throws ParseException {
        if (CheckUtil.strIsEmpty(body)) {
            return XieChengResponse.error();
        }
        switch (action) {
            case "productquery": {
                log.info("携程获取配置的订单价格参数：{}", body);
                QueryProductRequest request = JSON.parseObject(body, QueryProductRequest.class);
                return requestService.queryProduct(request);
            }
            case "ordercreate": {
                log.info("携程创建携程订单参数：{}", body);
                CreateOrderRequest request = JSON.parseObject(body, CreateOrderRequest.class);
                return requestService.createOrder(request);
            }
            case "updatepassengerinfo": {
                log.info("携程更新乘客订单参数：{}", body);
                UpdatePassengerRequest request = JSON.parseObject(body, UpdatePassengerRequest.class);
                return requestService.updatePassenger(request);
            }
            case "querydriverlocation": {
                log.info("携程查询司机的位置参数：{}", body);
                QueryDriverLocationRequest request = JSON.parseObject(body, QueryDriverLocationRequest.class);
                return requestService.queryDriverLocation(request);
            }
            case "ordercancel": {
                log.info("携程取消订单参数：{}", body);
                CancelOrderRequest request = JSON.parseObject(body, CancelOrderRequest.class);
                return requestService.cancelOrder(request);
            }
            case "vehicleinfo": {
                log.info("携程推送车辆信息参数：{}", body);
                PushVehicleInfoRequest request = JSON.parseObject(body, PushVehicleInfoRequest.class);
                return requestService.pushVehicleInfo(request);
            }
            case "cityinfo": {
                log.info("携程推送城市信息参数：{}", body);
                PushCityInfoRequest request = JSON.parseObject(body, PushCityInfoRequest.class);
                return requestService.pushCityInfo(request);
            }
        }
        return XieChengResponse.error();
    }

    /**
     * 开发者测试使用
     * @param request
     * @return
     */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public XieChengResponse test(@RequestBody QueryProductRequest request) throws ParseException {
        log.info("携程获取配置的订单价格参数：{}", request);
        return requestService.queryProduct(request);
    }

    @RequestMapping(value = "/testUpdatePassenger", method = RequestMethod.POST)
    public XieChengResponse testUpdatePassenger(@RequestBody UpdatePassengerRequest request) throws ParseException {
        log.info("携程获取配置的订单价格参数：{}", request);
        return requestService.updatePassenger(request);
    }

}
